package com.leedsoft.spittr.aop.proxy_test.cglib;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * Created by leeds on 2017/11/15.
 * 动态代理生成类
 */
public class ProxyCreator2 implements MethodInterceptor {//MethodInterceptor 提供通知逻辑切入点
    private BookFacadeImpl2 target;

    public ProxyCreator2(BookFacadeImpl2 target) {
        this.target = target;
    }

    public BookFacadeImpl2 getProxy() {
        Enhancer enhancer = new Enhancer();//Enhancer 动态生成委托类子类，将该子类对象作为代理对象
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(this);
        return (BookFacadeImpl2) enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("cglib 前置逻辑");
        Object result = method.invoke(target, objects);
        System.out.println("cglib 后置逻辑");
        return result;
    }

    public static void main(String[] args) {
        BookFacadeImpl2 bookFacade = new ProxyCreator2(new BookFacadeImpl2()).getProxy();
        bookFacade.addBook();
    }
}
